package com.zhkj.txg.utils

import android.app.Activity
import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.fragment.app.Fragment
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.filter.Filter
import com.zhihu.matisse.internal.entity.IncapableCause
import com.zhihu.matisse.internal.entity.Item
import com.zhihu.matisse.internal.utils.PathUtils
import java.io.File


object MatisseUtils {
    fun selectPicture(activity: Activity, requestCode: Int, count: Int = 1) {
        Matisse.from(activity)
            .choose(MimeType.of(MimeType.PNG, MimeType.JPEG))
            .addFilter(object : Filter() {
                override fun filter(context: Context?, item: Item?): IncapableCause? {
                    if (item != null) {
                        val path = PathUtils.getPath(context, item.contentUri)
                        if (File(path).exists()) return null
                        else deletePictures(context, item.contentUri)
                    }
                    return IncapableCause(IncapableCause.TOAST, "图片为空")
                }

                override fun constraintTypes(): MutableSet<MimeType> = mutableSetOf(MimeType.PNG, MimeType.JPEG)
            })
            .showSingleMediaType(true)
            .countable(count > 1).spanCount(3).maxSelectable(count)
            .imageEngine(GlideEngine()).forResult(requestCode)
    }

    fun selectPicture(fragment: Fragment, requestCode: Int, count: Int = 1) {
        Matisse.from(fragment)
            .choose(MimeType.of(MimeType.PNG, MimeType.JPEG))
            .addFilter(object : Filter() {
                override fun filter(context: Context?, item: Item?): IncapableCause? {
                    if (item != null) {
                        val path = PathUtils.getPath(context, item.contentUri)
                        if (File(path).exists()) return null
                    }
                    return IncapableCause(IncapableCause.TOAST, "图片为空")
                }

                override fun constraintTypes(): MutableSet<MimeType> = mutableSetOf(MimeType.PNG, MimeType.JPEG)
            })
            .showSingleMediaType(true)
            .countable(count > 1).spanCount(3).maxSelectable(count)
            .imageEngine(GlideEngine()).forResult(requestCode)
    }

    /**
     * 通知系统数据库删除已删除的图片的信息
     */
    private fun deletePictures(context: Context?, uri: Uri) {
        val delete = context?.contentResolver?.delete(uri, null, null)
        if (delete != null && delete >= 0) Log.e("deletePictures", "删除系统数据库成功")
        else Log.e("deletePictures", "删除系统数据库失败")
    }
}